package com.hk.sqlsession;

import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Map;

import com.hk.Executor.MyExecutor;
import com.hk.config.MyConfiguration;
import com.hk.configBean.MyMappedStatement;
import com.hk.proxy.MyMapperProxy;

/**
 * 所有的业务逻辑都在sqlSession中完成
 * getMapper(Class<?> ..)  通过动态代理生成xxxMapper 类，调用查询方法，
 * 查询也需要在sqlSession调用，需要操作数据库的都在Executor中实现。
 * 
 * @author le-px
 *
 */
public class SqlSession {

	private MyConfiguration myconfig;
	private MyExecutor executor;
	public SqlSession(MyConfiguration myconfig,MyExecutor executor) {
		this.myconfig = myconfig;
		this.executor = executor;
	}
	@SuppressWarnings("unchecked")
	public <T> T getMapper(Class<T> clazz) {
		return (T)Proxy.newProxyInstance(clazz.getClassLoader(), 
				         new Class<?>[] {clazz},
				         new MyMapperProxy(this));
	}

	public <T> Object selectOne(String methodName,Object[] args) {
		//交给MyExecutor去处理
		//得到MyMappedStatement 通过 key :namespace+id
		
		MyMappedStatement mapped = myconfig.getMap().get(methodName);
		//用一个list来存储结果集
		List<Object> resultList = executor.query(mapped, args);
		if(resultList!= null && resultList.size()>1) {
			throw new RuntimeException("查询结果多于一条");
		}else {
			return resultList.get(0);
		}
	}
	public <T> List<Object>  selectList(String methodName,Object[] args){
		//交给MyExecutor去处理
		//得到MyMappedStatement 通过 key :namespace+id
		
		MyMappedStatement mapped = myconfig.getMap().get(methodName);
		//用一个list来存储结果集
		List<Object> resultList = executor.query(mapped, args);
		return resultList;
	}
	public Map<Object,Object> selectMap(String methodName,Object args){
		
		return null;
	}
	
}
